// pages/addclock/addclock.js
var imageUtil = require('../../utils/util.js');
var util = require('../../utils/util.js');
import { Data } from './addclock.data';
var app = getApp();
Page({
  data: Data,
  onLoad: function (options) {
    var that = this;

    // 调用函数时，传入new Date()参数，返回值是日期和时间  
    var time = util.formatTime(new Date());
    // 再通过setData更改Page()里面的data，动态更新页面的数据  
    that.setData({
      'out4.starttime': time,
      'out12.getuptime':time,
    });  

    app.getUserInfo(function (userInfo) {
      that.setData({ userInfo: userInfo })
    })
    getnowtime(that);
    setInterval(function () {
      getnowtime(that)
    }, 60000);
    var type = options.type;
    var sign = options.sign;
    var times=options.times;


    //改变导航头的名称
    if (type == 11 & times == 1) {
      wx.setNavigationBarTitle({
        title: '早间运动'
      })
    }
    //改变导航头的名称
    if (type ==7 & times == 1) {
      wx.setNavigationBarTitle({
        title: '体温打卡'
      })
    }
    if (type == 11 & times == 2) {
      wx.setNavigationBarTitle({
        title: '上午运动'
      })
    }
    if (type == 11 & times == 4) {
      wx.setNavigationBarTitle({
        title: '下午运动'
      })
    }
    if (type == 11 &times == 6) {
      wx.setNavigationBarTitle({
        title: '夜间运动'
      })
    }
    if (type == 9 & times == 7) {
      wx.setNavigationBarTitle({
        title: '月经打卡'
      })
    }
    if (type == 12 & times == 1) {
      wx.setNavigationBarTitle({
        title: '起床时间'
      })
    }
    if (type == 6 & times == 1) {
      wx.setNavigationBarTitle({
        title: '早晨饮水'
      })
    }
    if (type == 6 & times == 2) {
      wx.setNavigationBarTitle({
        title: '上午饮水'
      })
    }
    if (type == 6 & times == 4) {
      wx.setNavigationBarTitle({
        title: '下午饮水'
      })
    }
    if (type == 1 & times == 1) {
      wx.setNavigationBarTitle({
        title: '早餐打卡'
      })
    }
    if (type == 4 & times == 2) {
      wx.setNavigationBarTitle({
        title: '上午加餐'
      })
    }
    if (type == 2 & times == 3) {
      wx.setNavigationBarTitle({
        title: '午餐加餐'
      })
    }
    if (type == 5 & times == 4) {
      wx.setNavigationBarTitle({
        title: '下午加餐'
      })
    }
    if (type == 3 & times == 5) {
      wx.setNavigationBarTitle({
        title: '晚餐打卡'
      })
    }
    if (type == 13 & times == 6) {
      wx.setNavigationBarTitle({
        title: '睡前准备'
      })
    }
    if (type == 12 & times == 6) {
      wx.setNavigationBarTitle({
        title: '睡眠时间'
      })
    }
    if (type == 14 & times == 6) {
      wx.setNavigationBarTitle({
        title: '运动加餐'
      })
    }

   
    //上、下午加餐
    if (type == 4 || type == 5||type==14) {
      var formSet = this.data.formSet2;
      var out = this.data.out2;
      this.setData({ 'formSet': formSet, 'out': out })
    }
    //喝水打卡
    if (type == 6) {
      var formSet = this.data.formSet3;
      var out = this.data.out3 = {};
      out['starttime'] = this.data.out4.starttime;
      this.setData({ 'formSet': formSet, 'out': out });
      var url = '/IbabyWebService/camp/dietHistoryToday?patientid=' + wx.getStorageSync('userInfo').patientid + '&type=' + type;
      app.https.get(that, url, {}, function (res) {
        try {
          var last = {}, total = 0;
          last.weight = parseInt(JSON.parse(res[0].detail).food[0].weight);
          last.time = JSON.parse(res[0].detail).starttime;
          for (var i = 0; i < res.length; i++) {
            var data = JSON.parse(res[i].detail);
            total = total + parseInt(data.food[0].weight);
          }
          that.setData({
            'last': last,
            'total': total
          });
        } catch (err) {
          console.log(err)
        }
      })
    }
    //基础体温打卡
    if (type == 7) {
      var formSet = this.data.formSet4;
      var out = this.data.out4;
      this.setData({ 'formSet': formSet, 'out': out });
      var url = '/IbabyWebService/camp/dietHistoryToday?patientid=' + wx.getStorageSync('userInfo').patientid + '&type=' + type;
      app.https.get(that, url, {}, function (res) {
        try {
          var last = {};
          last.temperature = JSON.parse(res[0].detail).temperature;
          last.time = JSON.parse(res[0].detail).starttime;
          that.setData({
            'last': last,
          });
        } catch (err) {
          console.log(err)
        }
      })
    }
    //体重打卡
    if (type == 8) {
      var formSet = this.data.formSet5;
      var out = this.data.out4;
      this.setData({ 'formSet': formSet, 'out': out });
      var url = '/IbabyWebService/camp/dietHistoryToday?patientid=' + wx.getStorageSync('userInfo').patientid + '&type=' + type;
      app.https.get(that, url, {}, function (res) {
        try {
          var last = {};
          last.weight = JSON.parse(res[0].detail).weight;
          last.time = JSON.parse(res[0].detail).starttime;
          that.setData({
            'last': last,
          });
        } catch (err) {
          console.log(err)
        }
      })
    }
    //月经打卡
    if (type == 9) {
      var formSet = this.data.formSet6;
      var out = this.data.out4;
      that.setData({ 'formSet': formSet, 'out': out });
      let url = '/aiding-web/api/camps?patientId=' + wx.getStorageSync('userInfo').patientid + '&start=0&size=3&type=9'
      app.https.get(that, url, {}, function (res) {
        try {
          var date = new Date();
          var year = date.getFullYear(),
            month = date.getMonth() + 1,
            day = date.getDate();
          month = (month < 10) ? '0' + month : month;
          day = (day < 10) ? '0' + day : day;
          out.starttime = year + '-' + month + '-' + day;
          console.log(out.starttime)
          that.setData({ 'formSet': formSet, 'out': out });
        } catch (err) {
          console.log(err)
        }
      })
    }

    //起床时间 或者 睡眠时间
    if(type==12){
      var out = this.data.out12;
      this.setData({'out': out });
      var url = '/IbabyWebService/camp/dietHistoryToday?patientid=' + wx.getStorageSync('userInfo').patientid + '&type=' + type;
      app.https.get(that, url, {}, function (res) {
        var list = res;
        if (that.data.times == 1) {
          for (var i = 0; i < list.length; i++) {
            if (list[i].times == 1) {
              try {
                var last = {};
                last.getuptime = JSON.parse(res[0].detail).getuptime;
                that.setData({
                  'last': last,
                });
              } catch (err) {
                console.log(err)
              }
            }else if(list[i].times==6){
              try {
                var last = {};
                last.getuptime = JSON.parse(res[0].detail).getuptime;
                that.setData({
                  'last': last,
                });
              } catch (err) {
                console.log(err)
              }
            }
          }

        }
        
      })
    }
   
    

    this.setData({ 'outtype': type, 'outsign': sign,"outtimes":times});
  },
  pickerImg: function () {
    var that = this;
    pickerimg(that);
  },
  //表单填写
  bindForm: function (e) {
    var key = e.currentTarget.dataset.key,
      value = e.detail.value;
    var data = {};
    data[key] = value;
    this.setData(data);
  },
  bindForm2: function (e) {
    let key = e.currentTarget.dataset.key,
      index = e.currentTarget.dataset.index,
      value = e.detail.value;
    var key1 = 'out.food[' + index + ']' + '.' + key;
    var key2 = 'out.food[' + index + ']' + '.' + "name";
    var data = {};
    data[key1] = value;
    this.setData(data);
    var _data = this.data.out;
    var data = {};
    data[key2] = e.currentTarget.dataset.name;
    this.setData(data)
  },
  //获取起床时间
  bindTimeChange: function (e) {

    var out = this.data.out12;
    this.setData({ 'out': out });
    this.setData({
      'out.getuptime': e.detail.value
    })
  },
  //睡前准备
  radioChangeA: function (e) {
    // var out = this.data.out13;
    // this.setData({'out': out });
    this.setData({
      readyA: e.detail.value
    })
    // console.log(this.data.out)
   
  },
  radioChangeB: function (e) {
    // var out = this.data.out13;
    // this.setData({'out': out });
    this.setData({
      readyB: e.detail.value
    })
    // console.log(this.data.out)
  },
  addFood: function () {
    var that = this, type = this.data.outtype;
    addfood(that, type);
  },
  
  
  //添加表单
  foodFormBlock: function () {
    var that = this;
    if (this.data.outtype == 6 || this.data.outtype == 7 || this.data.outtype == 8 || this.data.outtype == 9 || this.data.outtype == 12 || this.data.outtype == 13) {
      that.setData({ 'set.formBlock': true });
    } else {
      if (that.data.set.imgChanged) {
        that.setData({ 'set.formBlock': true });
      } else {
        that.setData({ 'set.showConsole': true });
      }
    }
  },
  resetForm: function () {
    this.setData({
      'set.formBlock': false
    });
  },
  submitData: function () {
    var that = this;
    submitdata(that);
  },
  temperatureone: function () {
    wx.redirectTo({

      url: '../temperatureone/temperatureone?type=' + this.data.outtype+'&times='+this.data.outtimes+'&sign='+this.data.outsign

    })
  },
  menstruationtwo: function () {
    wx.redirectTo({
      url: '../menstruation/menstruation?type=' + this.data.outtype+'&times='+this.data.outtimes+'&sign='+this.data.outsign
    })
  },

})

//提交打卡,校验表单
function addfood(that, type) {
  // var out = that.data.out;
  if (type == 1 || type == 2 || type == 3) {
    var out = that.data.out;
    // try {
    var data = out.food;
    if (
      (Boolean(data[0].value) && Boolean(data[0].weight)
      ) || (
        Boolean(data[1]['value']) && Boolean(data[1]['weight'])
      ) || (
        Boolean(data[2]['value']) && Boolean(data[2]['weight'])
      ) || (
        Boolean(data[3]['value']) && Boolean(data[3]['weight']))) {
      wx.showModal({
        title: '提示',
        content: '确定添加当前饮食清单吗？',
        success: function (res) {
          if (res.confirm) {
            that.setData({ 'set.formBlock': false, 'foodlist': true });
          }
        }
      })
    } else {
      that.setData({ 'set.formConsole': true, })
    }
  } else if (type == 4 || type == 5||type==14) {
    var out = that.data.out;
    try {
      var data = out.food;
      if (data[0]['value'] && data[0]['weight'] && out.starttime) {
        wx.showModal({
          title: '提示',
          content: '确定添加当前加餐清单吗？',
          success: function (res) {
            if (res.confirm) {
              that.setData({ 'set.formBlock': false, 'foodlist': true });
            }
          }
        })
      } else {
        that.setData({ 'set.formConsole': true, })
      }
    } catch (err) {
      that.setData({ 'set.formConsole': true, })
    }
  } else if (type == 6) {
    var out = that.data.out;
    var data = out.food;
    if (data[0]['weight'] && out.starttime) {
      wx.showModal({
        title: '提示',
        content: '确定添加当前喝水清单吗？',
        success: function (res) {
          var lastweight = parseInt(that.data.out.food[0].weight);
          var lasttime = that.data.out.starttime;
          data[0]['value'] = '水';
          var total = that.data.total + parseInt(lastweight);
          if (res.confirm) {
            that.setData({ 'set.formBlock': false, 'foodlist': true, 'total': total, 'last.time': lasttime, 'last.weight': lastweight, 'out.food': data });
          }
        }
      })
    } else {
      that.setData({ 'set.formConsole': true })
    }
  } else if (type == 7) {
    var out = that.data.out;
    var data = out;
    if (out.starttime && out.temperature) {
      wx.showModal({
        title: '提示',
        content: '确定添加体温打卡吗？',
        success: function (res) {
          var lasttime = that.data.out.starttime,
            temperature = that.data.out.temperature;
          if (res.confirm) {
            that.setData({ 'set.formBlock': false, 'foodlist': true, 'last.time': lasttime, 'last.temperature': temperature });
          }
        }
      })
    } else {
      that.setData({ 'set.formConsole': true })
    }
  } else if (type == 8) {
    var out = that.data.out;
    var data = out;
    if (out.starttime && out.weight) {
      wx.showModal({
        title: '提示',
        content: '确定添加体重打卡吗？',
        success: function (res) {
          var lasttime = that.data.out.starttime,
            lastweight = that.data.out.weight;
          if (res.confirm) {
            that.setData({ 'set.formBlock': false, 'foodlist': true, 'last.time': lasttime, 'last.weight': lastweight });
          }
        }
      })
    } else {
      that.setData({ 'set.formConsole': true })
    }
  } else if (type == 9) {
    var out = that.data.out;
    var data = out;
    if (out.starttime && out.duration) {
      wx.showModal({
        title: '提示',
        content: '确定提交打卡数据吗？',
        success: function (res) {
          submitdata(that);
          if (res.confirm) {
            that.setData({ 'set.formBlock': false, 'foodlist': true });
          }
        }
      })
    } else {
      that.setData({ 'set.formConsole': true })
    }
  }else if(type==12){
    var out = that.data.out;
    var data = out;
    if (out.getuptime){
      wx.showModal({
        title:'提示',
        content:'确定提交打卡数据吗？',
        success:function(res){
          var last={}
          var getuptime = that.data.out.getuptime;
          if(res.confirm){
            that.setData({ 'set.formBlock': false, 'foodlist': true, 'last.getuptime':getuptime})
          }
        }
      })
      
    }else{
      that.setData({ 'set.formConsole': true })
    }

  }else if(type==13){
    var out = that.data.out13;
    that.setData({'out': out });
    var readyA = that.data.readyA;
    var readyB = that.data.readyB;
    out.plans.push(readyA, readyB)

    that.setData({
      
      'out.plans': out.plans,
    })
    
    if (out.plans){
      console.log(out.plans)
      wx.showModal({
        title: '提示',
        content: '确定提交打卡数据吗？',
        success: function (res) {
          var last={}; 
          var plans=that.data.out.plans;
          if (res.confirm) {
            that.setData({ 'set.formBlock': false, 'foodlist': true, 'last.plans': plans })
          }
        }
      })

    } else {
      that.setData({ 'set.formConsole': true })
    }
  }
}

// //提交打卡
// function submitdata(that) {
//   var patientid = wx.getStorageSync('userInfo').patientid;
//   var detail = JSON.stringify(that.data.out);
//   var img = that.data.outimg;
//   var params = {
//     patientid: patientid,
//     img: img || null,
//     detail: detail,
//     type: that.data.outtype,
//   }
//   app.https.post(that, '/IbabyWebService/camp/submitDiet', params, function (res) {
//     if (that.data.outtype == 7 || that.data.outtype == 8) {
//       wx.redirectTo({
//         url: "../chart/chart?id=" + res.dietId + '&type=' + that.data.outtype
//       })
//     } else {
//       wx.redirectTo({
//         url: '../clock/clock?id=' + res.dietId + '&type=' + that.data.outtype + '&patientid=' + wx.getStorageSync('userInfo').patientid
//       })
//     }
//   })
// }

//提交打卡
function submitdata(that) {
  var patientid = wx.getStorageSync('userInfo').patientid;
  if (patientid == undefined || patientid == null) {
    wx.login({
      success: function (res) {
        var code = res.code;
        wx.getUserInfo({
          success: function (res) {
            var userinfo = res.userInfo;
            app.globalData.userInfo = res.userInfo;
            that.setData({ 'userInfo': userinfo });
            var params = {
              wxcode: code,
              username: userinfo.nickName,
              icon: userinfo.avatarUrl,
              city: userinfo.province
            };
            app.https.post(that, '/IbabyWebService/3/Patient/wxmpSignUp', params, function (res) {
              wx.setStorage({
                key: "userInfo",
                data: res
              })

             //异步缓存

              wx.getStorage({
                key: 'userInfo',
                success: function (res) {
                  var patientid = res.data.patientid;
                  var detail = JSON.stringify(that.data.out);
                  var img = that.data.outimg;
                  var params = {
                    patientid: patientid,
                    img: img || null,
                    detail: detail,
                    type: that.data.outtype,
                    times:that.data.outtimes,

                  }
                  app.https.post(that, '/IbabyWebService/camp/submitDiet', params, function (res) {
                    if (that.data.outtype == 7 || that.data.outtype == 8) {
                      wx.redirectTo({
                        url: "../chart/chart?id=" + res.dietId + '&type=' + that.data.outtype
                      })
                    } else {
                      wx.redirectTo({

                        url: '../clock/clock?id=' + res.dietId + '&type=' + that.data.outtype + "&sign=" + that.data.outsign + "&times=" + that.data.outtimes + '&patientid=' + wx.getStorageSync('userInfo').patientid

                      })
                    }
                  })

                },

              })

            })
          },
          fail: function () {
            // fail
            console.log('获取用户信息失败')
          }
        })
      },
      fail: function () {
        console.log('授权失败')
      },
    })

  } else {
    var detail = JSON.stringify(that.data.out);
    var img = that.data.outimg;
    var params = {
      patientid: patientid,
      img: img || null,
      detail: detail,
      type: that.data.outtype,
      times: that.data.outtimes,
    }
    app.https.post(that, '/IbabyWebService/camp/submitDiet', params, function (res) {
      if (that.data.outtype == 7 || that.data.outtype == 8) {
        wx.redirectTo({
          url: "../chart/chart?id=" + res.dietId + '&type=' + that.data.outtype
        })
      } else {
        wx.redirectTo({

          url: '../clock/clock?id=' + res.dietId + '&type=' + that.data.outtype+ "&sign=" + that.data.outsign + "&times=" + that.data.outtimes + '&patientid=' + wx.getStorageSync('userInfo').patientid

        })
      }
    })
  }

}




//获取当前时间
function getnowtime(that) {
  var date = new Date();
  var seperator1 = "-";
  var seperator2 = ":";
  var month = date.getMonth() + 1;
  var strDate = date.getDate();
  if (month >= 1 && month <= 9) { month = "0" + month; }
  if (strDate >= 0 && strDate <= 9) { strDate = "0" + strDate; }
  var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
    + " " + date.getHours() + seperator2 + date.getMinutes();
  that.setData({ 'set.time': currentdate })
}

//更换图片
function pickerimg(that) {

  wx.chooseImage({
    count: 1, // 最多可以选择的图片张数，默认9
    sizeType: ['compressed'], // original 原图，compressed 压缩图，默认二者都有
    sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
    success: function (res) {

      // success
      var imgpath = res.tempFilePaths[0];
      console.log(imgpath)
      wx.getImageInfo({
        src: imgpath,
        success: function (res) {
          var imageSize = imageUtil.imageUtil(res);
          var data = {};
          data['imageheight'] = imageSize.imageHeight;
          data['imagewidth'] = imageSize.imageWidth;
          that.setData(data);
        }

      })

      // //图片上传
      app.https.uploadfile(that, '/IbabyWebService/File/Upload', imgpath, function (res) {
        var imgpath = app.https.baseurl + res;
        console.log(imgpath)
        that.setData({
          'outimg': imgpath,
          'set.imgChanged': true,
          'set.showConsole': false
        });
      })
    }
  })
}